package com.boboPlanet.user.service.impl;

import cn.xuyanwu.spring.file.storage.FileInfo;
import com.boboPlanet.comm.context.LoginUserContext;
import com.boboPlanet.comm.entity.po.LoginUserInfoPO;
import com.boboPlanet.comm.filestorage.PlanetFileStorageTemplate;
import com.boboPlanet.user.async.AsyncTask;
import com.boboPlanet.user.entity.dto.SysLogDTO;
import com.boboPlanet.user.enums.SysOperatorEnum;
import com.boboPlanet.user.mapper.UserDetailOperationMapper;
import com.boboPlanet.user.mapper.UserResumeMapper;
import com.boboPlanet.user.single.SingleFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2023/3/13
 **/
@Slf4j
public class UploadFileHandlerImpl {

    /**
     * 文件基础地址,配置文件中 base-path
     */
    @Value("${spring.file-storage.local-plus[0].base-path}")
    private String BASE_URL;

    @Resource
    private PlanetFileStorageTemplate planetFileStorageTemplate;


    private final UserDetailOperationMapper userDetailOperationMapper;

    private final UserResumeMapper userResumeMapper;

    private final AsyncTask asyncTask;

    /**
     * 公共构造注入  所有方法都用到的属性从此构造注入
     * @param asyncTask AsyncTask 异步任务
     */
    public UploadFileHandlerImpl(AsyncTask asyncTask, UserDetailOperationMapper userDetailOperationMapper, UserResumeMapper userResumeMapper ){
        this.asyncTask = asyncTask;
        this.userDetailOperationMapper = userDetailOperationMapper;
        this.userResumeMapper = userResumeMapper;
    }


    /**
     * 上传用户简历头像
     * @param file File
     * @return FileName
     */
    public String uploadResumeAvatar(MultipartFile file){
        LoginUserInfoPO userInfo = LoginUserContext.getLoginUserInfoPO();

        String oldFileName = userResumeMapper.getResumeUrlByUserId(userInfo.getUserId());
        FileInfo fileInfo = planetFileStorageTemplate.uploadFile(file, "", "");
        if (ObjectUtils.isEmpty(fileInfo)){
            return StringUtils.EMPTY;
        }
        List<SysLogDTO> dtoList = new ArrayList<>();
        SysLogDTO logDto = SingleFactory.getLogDto(SysOperatorEnum.upload_resume_avatar.getDesc()+",账户id:"+userInfo.getAccountId());
        if (StringUtils.isNotBlank(oldFileName)){
            boolean delete = planetFileStorageTemplate.delete(BASE_URL + "/" + oldFileName);
            //boolean delete = fileStorageService.delete(BASE_URL + "/" + oldFileName);
            if (delete){
                SysLogDTO delLog = SingleFactory.getLogDto(SysOperatorEnum.delete_resume_old_avatar.getDesc()+",账户id:"+userInfo.getAccountId());
                dtoList.add(delLog);
            }else {
                log.error("delete user resume avatar fail,old file name is: {}, userId is: {}",oldFileName,userInfo.getUserId());
            }
        }
        dtoList.add(logDto);
        asyncTask.batchTranceLog(dtoList);

        return fileInfo.getFilename() == null || Objects.equals(fileInfo.getFilename(), "") ? StringUtils.EMPTY : fileInfo.getFilename();

    }


    /**
     * 上传用户头像
     * @param file  MultipartFile
     * @param fileType String
     * @return URL
     */
    public String uploadUserAvatar(MultipartFile file, String fileType){
        LoginUserInfoPO userInfo = LoginUserContext.getLoginUserInfoPO();

        String oldUrl = userDetailOperationMapper.queryAvatarUrlById(userInfo.getUserId());

        //fileType：image/png格式
        String suffix = fileType.substring(fileType.lastIndexOf("/") + 1);
        FileInfo fileInfo = planetFileStorageTemplate.uploadFile(file, "", suffix);

        if (ObjectUtils.isEmpty(fileInfo)){
            return StringUtils.EMPTY;
        }
        //fileName带后缀的
        String fileName = fileInfo.getFilename();
        userDetailOperationMapper.updateUserAvatarById(userInfo.getUserId(),fileInfo.getUrl() ,fileName);

        SysLogDTO logDto = SingleFactory.getLogDto(SysOperatorEnum.UPDATE_USER_AVATAR.getDesc()+",账户id:"+userInfo.getAccountId());
        List<SysLogDTO> dtoList = new ArrayList<>();
        dtoList.add(logDto);
        //删除服务器上原来的
        if (StringUtils.isNotBlank(oldUrl)){
            boolean delete = planetFileStorageTemplate.delete(oldUrl);
            //boolean delete = fileStorageService.delete(oldUrl);
            if (delete){
                SysLogDTO delLog = SingleFactory.getLogDto(SysOperatorEnum.delete_user_avatar.getDesc()+",账户id:"+userInfo.getAccountId());
                dtoList.add(delLog);
            }else {
                log.error("delete user avatar fail,old url is: {}, userId is: {}",oldUrl,userInfo.getUserId());
            }
        }

        asyncTask.batchTranceLog(dtoList);

        return fileInfo.getUrl() == null || Objects.equals(fileInfo.getUrl(), "") ? StringUtils.EMPTY : fileInfo.getUrl();
    }

}
